﻿using System;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;

namespace EasySite.Infrastructure.Extensions
{
    public static class HtmlHelperExtensions
    {
        public static IHtmlString RoundPanel(this HtmlHelper htmlHelper, string title, Func<object, object> contentTemplate)
        {
            return htmlHelper.RoundPanel(o => title, contentTemplate, null, null);
        }

        public static IHtmlString RoundPanel(this HtmlHelper htmlHelper, string title, Func<object, object> contentTemplate, object htmlAttributes)
        {
            return htmlHelper.RoundPanel(o => title, contentTemplate, null, htmlAttributes);
        }

        public static IHtmlString RoundPanel(this HtmlHelper htmlHelper, Func<object, object> titleTemplate, Func<object, object> contentTemplate, Func<object, object> footerTemplate, object htmlAttributes)
        {
            RouteValueDictionary attrs = null;
            if (htmlAttributes != null)
            {
                attrs = HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes);
            }
            const string layout = @"
<div class='round-panel{3}'{4}>
    <div class='rp-top'>
        <div class='rp-top-l'></div>
        <div class='rp-top-r'></div>
        <div class='rp-top-m'>{0}</div>
        <div class='clear'></div>
    </div>
    <div class='rp-content'>
        <div class='rp-content-inner'>
            {1}
        </div>
    </div>
    <div class='rp-bottom'>
        <div class='rp-bottom-l'></div>
        <div class='rp-bottom-r'></div>
        <div class='rp-bottom-m'>{2}</div>
        <div class='clear'></div>
    </div>
</div>";
            var css = string.Empty;
            var attributes = string.Empty;
            if (attrs != null)
            {
                foreach (var attr in attrs)
                {
                    if (attr.Key.Equals("class", StringComparison.OrdinalIgnoreCase))
                    {
                        css = " " + attr.Value.ToString().Trim();
                    }
                    else
                    {
                        attributes += string.Format(" {0}=\"{1}\"", attr.Key, attr.Value);
                    }
                }
            }
            var title = string.Empty;
            var content = string.Empty;
            var footer = string.Empty;
            if (titleTemplate != null)
            {
                title = titleTemplate(null).ToString();
            }
            if (contentTemplate != null)
            {
                content = contentTemplate(null).ToString();
            }
            if (footerTemplate != null)
            {
                footer = footerTemplate(null).ToString();
            }
            return htmlHelper.Raw(string.Format(layout, title, content, footer, css, attributes));
        }
    }
}
